import { SearchOutlined } from '@ant-design/icons';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Button, Input, Modal, message } from 'antd';
import { useNavigate } from 'react-router-dom'
import { getManageTableList, shelfOFFByID, doOperateForProduct } from "@/api/service/manageService"
import { TableListItem } from "#/entity"
import { useSelector } from 'react-redux'


export default function Manage() {
  const [messageApi, contextMSG] = message.useMessage();
  const user = useSelector((state: any) => state.user.userInfo)
  const isAdmin = user && user.role && user.role.label === "admin"
  console.log(isAdmin ? "是超级管理员" : "普通用户");

  const config = {
    title: '确认下线！',
    content: (
      <>
        下线商品后，如需再上线必须重新发起审批流程！
      </>
    ),
  };
  const navigate = useNavigate()
  const tailColums: ProColumns<TableListItem>[] = [
    {
      title: '状态',
      dataIndex: 'status',
      initialValue: 'all',
      filters: true,
      onFilter: true,
      valueEnum: {
        all: { text: '全部', status: 'Default' },
        close: { text: '已下线', status: 'Default' },
        online: { text: '已上线', status: 'Success' },
        reviewing: { text: '审核中', status: 'Warning' }
      },
    },
    {
      title: '操作',
      width: 140,
      key: 'option',
      valueType: 'option',
      render: (text, record, action, schema) => [
        <Button onClick={() => navigate(`/workbench/productdetail/${record.productID}`)} size="small" type="primary">
          查看
        </Button>,
        isAdmin || <Button onClick={async () => {
          const confirmed = await modal.confirm(config);
          console.log('Confirmed: ', confirmed);
          if (confirmed) {
            doOperateForProduct({
              productID: record.productID,
              operatPerson: record.creator,
              status: "下架商品",
              comment: "下架商品~~~~~~~~~~",
            }).then(() => {
              shelfOFFByID(record.productID).then(val => {
                // 进行刷新操作！
                schema.reload()
                messageApi.open({
                  type: 'success',
                  content: '下架商品成功',
                });
              }).catch(err => {
                console.log(err);
                
              })
            })

          }
        }}
          disabled={record.status !== 'online'} danger size="small" type="primary">
          下线
        </Button>
      ],
    }
  ]
  //模板
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '排序',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '商品 ID',
      dataIndex: 'productID',
      render: (_) => <a>{_}</a>,
      // 自定义筛选项功能具体实现请参考 https://ant.design/components/table-cn/#components-table-demo-custom-filter-panel
      filterDropdown: () => (
        <div style={{ padding: 8 }}>
          <Input style={{ width: 188, marginBlockEnd: 8, display: 'block' }} />
        </div>
      ),
      filterIcon: (filtered) => (
        <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      render: (_) => <a>{_}</a>,
    },
    {
      title: '库存',
      dataIndex: 'containers',
      sorter: (a, b) => a.containers - b.containers
    },
    {
      title: '上架时间',
      dataIndex: 'shelf_on',
      valueType: 'date',
      key: 'showTime1',
      sorter: (a, b) => a.shelf_on - b.shelf_on,
      hideInSearch: true,
    },
    {
      title: '上架时间',
      dataIndex: 'shelf_on',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
    },
    {
      title: '下架时间',
      dataIndex: 'shelf_off',
      valueType: 'date',
      key: 'showTime2',
      sorter: (a, b) => a.shelf_off - b.shelf_off,
      hideInSearch: true,
    },
    {
      title: '下架时间',
      dataIndex: 'shelf_off',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
    }
  ];
  if (isAdmin) {
    columns.push(
      {
        title: '创建者',
        dataIndex: 'creator',
        valueEnum: {
          all: { text: '全部' },
          小雨: { text: '小雨' },
          xiaoer123: { text: 'xiaoer123' },
          react: { text: 'react' },
        },
      }
    )
  } else {
    Object.assign(tailColums[0].valueEnum, {
      error: { text: '审核失败', status: 'Error' },
      success: { text: '审核通过', status: 'Success' }
    })
  }
  columns.push(...tailColums)
  const [modal, contextHolder] = Modal.useModal();
  return (
    <>
      {contextHolder}
      {contextMSG}
      <ProTable<TableListItem>
        columns={columns}
        request={(params, sorter, filter) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          console.log(params, sorter, filter);


          return new Promise((resolve2, reject2) => {
            getManageTableList(params, sorter, filter).then(val => {
              resolve2({
                data: val,
                success: true,
              })
            }).catch(err => {
              reject2(err)
            })
          })

        }}
        rowKey="key"
        pagination={{
          showQuickJumper: true,
        }}
        search={{
          layout: 'vertical',
          defaultCollapsed: false,
        }}
        dateFormatter="string"
        toolbar={{
          title: '商品列表',
          tooltip: '商品管理列表，双击列表项和点击后面的操作按钮可以跳转到详情界面',
        }}
        toolBarRender={() => [
          isAdmin || <Button type="primary" key="primary" onClick={() => navigate('/workbench/addproduct')}>
            创建商品
          </Button>
        ]}
      />
    </>
  );
};